package com.zk.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zk.model.export.ApprovalOpinion;
import com.zk.model.export.GmspPdf;
import com.zk.util.DateUtil;
import com.zk.util.FileUtil;
import com.zk.util.FreemarkerWordUtil;
import com.zk.util.Word2PdfUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.core5.http.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ZHAIKE
 * @date 2024/10/17 15:05
 */
@Slf4j
@Service
public class ExportService {

    /**
     * 规模审批导出
     */
    public void downloadGmsp(
            String processInstanceId,
            String tab,
            Long dataId,
            Long catchDataId,
            HttpServletResponse response)
            throws IOException {
        List<String> approvalRoleList =
                Arrays.asList("支行行长", "分行公司部审核岗", "分行公司部经理", "分行分管行长", "规模审批岗", "总行公司金融部");
        Map<String, Object> docMap = this.getInitGmspDocMap(approvalRoleList);
        Map<String, String> param = new HashMap<>();
        // 暂存时processInstanceId为空
        /*if (StringUtils.isNotBlank(processInstanceId)) {
            // 获取审批流程进度
            param.put("userId", String.valueOf(UserInfoUtil.getUserId()));
            param.put("processInstanceId", processInstanceId);
            if (StringUtils.isNotBlank(tab)) {
                param.put("tab", tab);
            }
            String workFlowUrl =
                    WebConfig.YS_WORKFLOW_DOMAIN
                            + "/pending/getProcessLogDetail"
                            + "?"
                            + makeUrlEncodedString(param);
            String workFlowingJSONStr = HttpUtil.doGet(workFlowUrl, 60000);
            JSONObject workFlowJSON = getRetJson("workFlowing", workFlowingJSONStr);
            if (workFlowJSON != null) {
                // 获取审批中的处理情况
                JSONArray processLogList = workFlowJSON.getJSONArray("processLogList");
                for (Object o : processLogList) {
                    JSONObject json = (JSONObject) o;
                    String approvalRole = json.getString("taskName");
                    if (approvalRoleList.contains(approvalRole)) {
                        ApprovalOpinion opinion = this.getApprovalOpinion(json);
                        if (null != opinion) {
                            docMap.put(approvalRole, opinion);
                        }
                    } else {
                        if (StringUtils.isNotBlank(json.getString("processNo"))) {
                            docMap.put("processNo", json.getString("processNo"));
                        }
                    }
                }
            }
        }
        // 获取表单的数据
        param = new HashMap<>();
        String dataJSONStr;
        if (dataId != null) {
            param.put("dataId", String.valueOf(dataId));
            String fromDataUrl =
                    WebConfig.YS_FORM_DOMAIN + "/formDataValue/dataEcho" + "?" + makeUrlEncodedString(param);
            dataJSONStr = HttpUtil.doGet(fromDataUrl, 60000);
        } else {
            if (catchDataId == null) {
                throw new BusinessException("抱歉，服务异常", ServiceResponseStatus.SYSTEM_ERROR);
            }
            param.put("id", String.valueOf(catchDataId));
            String fromDataUrl =
                    WebConfig.YS_FORM_DOMAIN
                            + "/userFormTask/getFormDataCacheById"
                            + "?"
                            + makeUrlEncodedString(param);
            dataJSONStr = HttpUtil.doGet(fromDataUrl, 60000);
        }

        JSONObject dataJSON = getRetJson("from", dataJSONStr);

        if (dataJSON != null) {
            // 表格数据
            JSONArray formDataJson = dataJSON.getJSONArray("formDataJson");
            for (Object o : formDataJson) {
                JSONObject jsonObject = (JSONObject) o;
                if (jsonObject.containsKey("value")) {
                    switch (jsonObject.getString("key")) {
                        case "qhu0d0x2e8lj":
                            if ("纯新增".equals(jsonObject.get("value"))) {
                                docMap.put("cxzCheck", true);
                                docMap.put("clCheck", false);
                                docMap.put("clxzCheck", false);
                            } else if ("存量新增".equals(jsonObject.get("value"))) {
                                docMap.put("cxzCheck", false);
                                docMap.put("clCheck", true);
                                docMap.put("clxzCheck", false);
                            } else if ("存量续作".equals(jsonObject.get("value"))) {
                                docMap.put("cxzCheck", false);
                                docMap.put("clCheck", false);
                                docMap.put("clxzCheck", true);
                            }
                            break;
                        case "qhu0fvvuihgv":
                            // 拟实现时间节点
                            String timevalue = "";
                            if (jsonObject.containsKey("value")
                                    && jsonObject.getString("value") != null
                                    && !"".equals(jsonObject.getString("value"))) {
                                timevalue = this.formatDate(jsonObject.getString("value"));
                            }
                            docMap.put(jsonObject.getString("key"), timevalue);
                            break;
                        case "qfwaitncfj5n":
                            JSONArray jsonArray = jsonObject.getJSONArray("value");
                            if (!CollectionUtils.isEmpty(jsonArray)) {
                                List<GmspPdf> situationList =
                                        JsonEasyUtil.json2List(jsonArray.toJSONString(), GmspPdf.class);
                                situationList.forEach(dto -> dto.setTime(this.formatDate(dto.getTime())));
                                docMap.put(jsonObject.getString("key"), situationList);
                            }
                            break;
                        case "qfwa8huaqjyl":
                            // 上下游联动情况
                        case "qfwa8it878m1":
                            // 公私联动情况
                        case "qfwa8jgu50gw":
                            // 其他贡献/特殊贡献
                            JSONArray array = jsonObject.getJSONArray("value");
                            if (!CollectionUtils.isEmpty(array)) {
                                List<GmspPdf> situationList =
                                        JsonEasyUtil.json2List(array.toJSONString(), GmspPdf.class);
                                situationList.forEach(dto -> dto.setTime(this.formatDate(dto.getTime())));
                                docMap.put(jsonObject.getString("key"), situationList.get(0));
                                if (situationList.size() > 1) {
                                    situationList.remove(0);
                                    docMap.put(jsonObject.getString("key") + "Array", situationList);
                                }
                            }
                            break;
                        default:
                            // 普通字段
                            docMap.put(jsonObject.getString("key"), jsonObject.get("value"));
                            break;
                    }
                }
            }
            // 审批编号
            if (dataJSON.containsKey("processNo")
                    && (!docMap.containsKey("processNo") || "".equals(docMap.get("processNo")))) {
                docMap.put("processNo", dataJSON.get("processNo"));
            }
        }*/

        String name = "规模审批";
        String outputDocPath = getOutputPath(name, "doc");
        String outputPdfPath = getOutputPath(name, "pdf");
        try {
            // java freemarker生成doc
            String templateFileName = name + ".ftl";
            FreemarkerWordUtil.createWord(docMap, templateFileName, outputDocPath);
            InputStream docInputStream = new FileInputStream(new File(outputDocPath));
            Word2PdfUtil.doc2Pdf(docInputStream, outputPdfPath);
            docInputStream.close();

            // 文件上传
            File pdfFile = new File(outputPdfPath);
            FileInputStream fileInputStream = new FileInputStream(pdfFile);
            MultipartFile multipartFile =
                    new MockMultipartFile(
                            pdfFile.getName(),
                            pdfFile.getName(),
                            ContentType.APPLICATION_OCTET_STREAM.toString(),
                            fileInputStream);
            /*ResultLong longResult = uploadLinkUploadFile(multipartFile, name);
            fxCommFileService.dw2(longResult, response);*/
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtil.deleteFile(outputDocPath);
            FileUtil.deleteFile(outputPdfPath);
        }
    }

    private String getOutputPath(String name, String fileType) {
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        return getBashPath() + name + "-" + date + "." + fileType;
    }

    private String getBashPath() {
        String os = System.getProperty("os.name").toLowerCase();
        File path = null;
        try {
            if (os.contains("windows")) {
                path = new File(ResourceUtils.getURL("classpath:\\").getPath());
            } else {
                path = new File(ResourceUtils.getURL("classpath:/").getPath());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (path == null || !path.exists()) {
            path = new File("");
        }
        String bashPath = path.getAbsolutePath() + "/";
        log.info(bashPath);
        File file = new File(bashPath);
        if (!file.exists() && !file.isDirectory()) {
            log.info("目录不存在");
            boolean mkdir = file.mkdir();
            if (mkdir) {
                log.info("文件夹：{}，创建成功", bashPath);
            } else {
                log.info("文件夹：{}，创建失败", bashPath);
            }
        } else {
            log.info("目录存在");
        }
        return bashPath;
    }

    private Map<String, Object> getInitGmspDocMap(List<String> approvalRoleList) {
        Map<String, Object> docMap = new HashMap<>();
        // 审批意见
        approvalRoleList.forEach(o -> docMap.put(o, new ApprovalOpinion().init()));
        docMap.put("processNo", "");
        // 字段
        docMap.put("qfw9upt8j2fk", "");
        docMap.put("qfw9v18bjexr", "");
        docMap.put("qfw9uys2q69i", "");
        docMap.put("qfw9v09pww0g", "");
        docMap.put("qfw9v1tty488", "");
        docMap.put("qfw9v2exyoxw", "");
        docMap.put("qfw9uqgw7p8m", "");
        docMap.put("qfw9urab8jgq", "");
        docMap.put("qfw9utf72a39", "");
        docMap.put("qfw9uvtopwdl", "");
        docMap.put("qfw9uwl97292", "");
        docMap.put("qfw9usin0mw8", "");
        docMap.put("qfwa3yeji5qm", "");
        docMap.put("qfwa40ihw2hx", "");
        docMap.put("qfwa41aen92h", "");
        docMap.put("qhu0ekgm6den", "");
        docMap.put("qfwa41wdr3e1", "");
        docMap.put("qfwa6d00tr25", "");
        docMap.put("qfwa6esq2lfj", "");
        docMap.put("qfwa6v0nuync", "");
        docMap.put("qfwa7efqrff1", "");
        docMap.put("qfwa7wsg30af", "");
        docMap.put("qhu0fvvuihgv", "");
        docMap.put("qfwa9tuxy989", "");
        docMap.put("qfwa8k1qe0ji", "");
        docMap.put("qml7pwk25s7d", "");
        docMap.put("qml7os41ous5", "");
        docMap.put("qmla2w2v2emj", "");
        docMap.put("qmla2wwmvj82", "");
        docMap.put("qmla3mftmidm", "");
        docMap.put("qmla3o1g87n9", "");
        docMap.put("qmla45k51rxr", "");
        docMap.put("qmla46ew7cpu", "");
        docMap.put("qmla475yk3he", "");
        docMap.put("qfwaah6u4vbh", "");
        // 勾选框
        docMap.put("qhu0d0x2e8lj", "");
        // 列表
        docMap.put("qfwa8huaqjyl", new GmspPdf().init());
        docMap.put("qfwa8it878m1", new GmspPdf().init());
        docMap.put("qfwa8jgu50gw", new GmspPdf().init());
        docMap.put("qfwaitncfj5n", new ArrayList<>());
        docMap.put("qfwa8huaqjylArray", new ArrayList<>());
        docMap.put("qfwa8it878m1Array", new ArrayList<>());
        docMap.put("qfwa8jgu50gwArray", new ArrayList<>());
        return docMap;
    }

    public ApprovalOpinion getApprovalOpinion(JSONObject jsonObject) {
        JSONArray taskList = jsonObject.getJSONArray("taskList");
        if (CollectionUtils.isEmpty(taskList)) {
            return null;
        }
        // 1 - 同意、2 - 拒绝、5 - 加签
        List<String> statusList = Arrays.asList("1", "2", "5");
        return taskList.stream()
                .map(o -> (JSONObject) o)
                .filter(json -> statusList.contains(json.getString("assigneeStatus")))
                .map(
                        json -> {
                            ApprovalOpinion opinion = new ApprovalOpinion();
                            opinion.setComment(json.getString("comment"));
                            opinion.setAssignee(json.getString("assignee"));
                            opinion.setEndTime(this.formatDate(json.getString("endTime")));
                            return opinion;
                        })
                .findFirst()
                .orElse(null);
    }

    private String formatDate(String date) {
        return DateUtil.toStrFromDate(
                DateUtil.toDateFromStr(date, DateUtil.YYYY_MM_DD), DateUtil.CN_YYYY_MM_DD);
    }
}
